from flask import render_template, redirect, url_for
from flask_login import current_user
from . import user
from models import User, GestureRecord
from user_management import add_user, delete_user, export_history

@user.route('/user_management')
def user_management():
    if current_user.role != 'admin':
        return redirect(url_for('gesture.recognition'))
    
    users = User.query.all()
    for user in users:
        user.records = GestureRecord.query.filter_by(user_id=user.id)\
            .order_by(GestureRecord.timestamp.desc())\
            .limit(3).all()
    
    return render_template('user_management.html', users=users)

@user.route('/add_user', methods=['POST'])
def add_user_route():
    return add_user()

@user.route('/delete_user/<int:user_id>', methods=['POST'])
def delete_user_route(user_id):
    return delete_user(user_id)

@user.route('/export_history')
def export_history_route():
    return export_history()

@user.route('/user_records')
def user_records():
    if current_user.role != 'admin':
        return redirect(url_for('gesture.recognition'))

    users = User.query.all()
    # 使用left join来包含所有记录，包括没有关联用户的记录
    records = GestureRecord.query.outerjoin(User).order_by(GestureRecord.timestamp.desc()).all()
    
    for record in records:
        if record.user_id:
            user = User.query.get(record.user_id)
            record.username = user.username if user else "未知用户"
        else:
            record.username = "未知用户"
            
    return render_template('user_records.html', users=users, records=records) 